<?php
/**
 * Адаптер для авторизації в системі
 *
 * @package zf-test
 * @subpackage Model
 * @author ihoros
 */

class Auth_Adapter implements Zend_Auth_Adapter_Interface {
    private $_authResult = Zend_Auth_Result::FAILURE;
    private $_idUser = null;
    private static $sleepTime = 3;

    /**
     * Construct the object.
     *
     * Construct object, with checking user credentials,
     * setup the result code, and user identity for futher usage.
     *
     * @param string $login
     * @param string $password
     */
    public function __construct($login, $password) {
        try {
            $auth = new Zend_Config_Ini(APPLICATION_PATH . '/configs/auth.ini',
                                        APPLICATION_ENV);
            $secret = $auth->auth->secret;
            $password = md5("test-constructor-" . $password . $secret);
            $accounts = $auth->accounts->toArray();
            
            if (array_key_exists($login, $accounts) && 
                    $password == $accounts[$login]['password'])
            {
                $this->_idUser = $login;
                $this->_authResult = Zend_Auth_Result::SUCCESS;
            }
        } catch ( Exception $e ) {
            $this->_authResult = $e->getCode();
        }
    }

    /**
     * Authentication.
     *
     * Just return the zend authentication result object with result code,
     * and user identity.
     *
     * @see Zend_Auth_Adapter_Interface
     * @return Zend_Auth_Result
     */
    public function authenticate() {
        return new Zend_Auth_Result($this->_authResult, $this->_idUser);
    }

    /**
     * Ожидание
     *
     * Защита от подбора паролей с возможностью изменения времени ожидания
     */
    static public function sleep()
    {
        return sleep(self::$sleepTime);
    }
}
